import { defineStore } from 'pinia';

import { getAllSimpleUserlist, getUserInfo, login, refreshToken as refreshTokenApi } from '@/api/permission';
import { usePermissionStore, useTabsRouterStore } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  id: undefined,
  deptId: undefined,
  nickname: '',
  avatar: '',
  roles: [],
};

export const useUserStore = defineStore('user', {
  state: () => ({
    tenantId: '',
    token: '',
    refreshToken: '',
    userInfo: { ...InitUserInfo },
    simpleList: [],
  }),
  getters: {
    // roles: (state) => {
    //   return state.userInfo?.roles;
    // },
    simpleUserList: (state) => {
      return state.simpleList;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const res = await login(userInfo);
      this.token = res.accessToken;
      this.refreshToken = res.refreshToken;
    },
    async getUserInfo() {
      const res = await getUserInfo();
      this.userInfo = { ...res.user, roles: res.roles };
      const permissionStore = usePermissionStore();
      permissionStore.temporaryMenus = res.menus;
      permissionStore.permissions = res.permissions;
      getAllSimpleUserlist().then((data) => {
        this.simpleList = data;
      });
    },
    async logout() {
      this.tenantId = '';
      this.token = '';
      this.refreshToken = '';
      this.userInfo = { ...InitUserInfo };
      const tabsRouterStore = useTabsRouterStore();
      tabsRouterStore.removeTabRouterList();
    },
    async updateRefreshToken() {
      const res = await refreshTokenApi({ refreshToken: this.refreshToken });
      this.token = res.accessToken;
      this.refreshToken = res.refreshToken;
    },
    getUserNameById(id: number) {
      return this.simpleList.find((item) => item.id === id)?.nickname;
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['tenantId', 'token', 'refreshToken'],
  },
});
